<?php

namespace app\api\controller;


use app\admin\model\AppSlider;
use app\admin\model\CashcardUser;
use app\admin\model\SystemConfig;
use app\api\service\wechat\WechatCheckServer;

class Index extends Api
{

    /**
     * @title 开启微信服务验证用
     * @author FashionJune
     */
    public function check()
    {
        WechatCheckServer::init()->checkServer()->send();
        exit;
    }

    public function notFound()
    {
        return $this->fetch('404');
    }

    public function index()
    {
        return $this->fetch();
    }

    public function about()
    {
        $about_html = SystemConfig::init()->getConfig('site_about');
//        dd($about_html);
        return $this->fetch('', [
            'about_us' => html_entity_decode($about_html)
        ]);
    }

    public function jsSDK()
    {
        $functions = str2arr(input('function_list'));
        $this->wechat->jssdk->setUrl(get_api_url('index', 'api'));
        $res = $this->wechat->jssdk->buildConfig($functions, false);
        return $res;
    }


    /**
     * @title 获取首页banner图
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author FashionJune
     */
    public function getAppBanner()
    {
        $count = AppSlider::init()->count();
        $list_data = AppSlider::init()->page($this->page, $this->per)->select();
        api_list_return($count, $list_data);
    }

    /**
     * @title 获取附近好店
     * @author FashionJune
     */
    public function getNearbyStore()
    {
        $lat = input('lat' ,null);
        $lng = input('lng', null);
        if (!$lat || !$lng) {
            api_error('无法正确获取您的位置，请确认定位权限已打开');
        }
        $max_distance = input('distance', sysconfig('rule', 'rule_store_distance'));
        $limit = input('limit', 4);
        $card_type = input('card_type', 0);
        //获取会员拥有的卡券
        $card_package = CashcardUser::init()->getUserPackage($this->user['user_id']);
        $global = false;
        in_array('', $card_package) && ($global == true);
        //预先用redis获取处理范围内所有店铺
        $stores_nearby = $this->redis->georadius('stores', $lng, $lat, $max_distance, 'm', ['WITHDIST', 'ASC']);
        $stores = [];
        $i = 0;
        foreach ($stores_nearby as $store) {
            $store_info = json_decode($this->redis->get('store_' . $store[0]));
            if ($card_type && ($card_type != $store_info->cate_id)) {//限制可使用券的种类
                continue;
            }
            if (!$store_info) {
                continue;
            }
            $store_info->distance = floor($store[1]) ?? 0;
            $store_info->cashcard_available = (in_array('', $card_package) || in_array($store_info->cate_id, $card_package));
            $stores[] = $store_info;
            if (++$i > $limit) {
                break;
            };
        }
        api_list_return(count($stores), $stores);
    }


}
